package com.glamour.hlcity.module.dom.analysis.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.openide.util.lookup.ServiceProvider;

import com.glamour.hlcity.common.data.model.ClassifiedKey;
import com.glamour.hlcity.common.data.model.ClueNode;
import com.glamour.hlcity.common.data.model.TagAttribute;
import com.glamour.hlcity.common.data.model.TagNode;
import com.glamour.hlcity.common.enums.ClassifiedEnum;
import com.glamour.hlcity.common.model.Node;
import com.glamour.hlcity.common.util.ListUtil;
import com.glamour.hlcity.module.dom.analysis.Classified;
import com.glamour.hlcity.module.dom.analysis.ClueClassified;
/**
 * 
 * 通用的归类
 * @author zhaoxing.liuzx
 *
 */

public abstract class GeneralClueClassified implements ClueClassified {

	@Override
	public void classified(ClueNode cludNode) {
		//聚合
		Map<String,List<Node>> classifiedMap=classifiedNodes(cludNode.getNodeList());
		cludNode.setNodeMap(renderMap(classifiedMap, getClassifiedEnum()));
	}
	
	/**
	 * map 渲染
	 * @param classifiedMap
	 * @return
	 */
	private Map<ClassifiedKey,List<Node>> renderMap(Map<String,List<Node>> classifiedMap,ClassifiedEnum classifiedEnum){
		Map<ClassifiedKey, List<Node>> map = new HashMap<ClassifiedKey, List<Node>>();
		Set<Map.Entry<String, List<Node>>> set = classifiedMap.entrySet();
		for (Iterator<Map.Entry<String, List<Node>>> it = set.iterator(); it
				.hasNext();) {
			Map.Entry<String, List<Node>> entry = (Map.Entry<String, List<Node>>) it
					.next();
			map.put(new ClassifiedKey(classifiedEnum, entry.getKey()),
					entry.getValue());
		}
		return map;
	}
	
	/**
	 * 聚合
	 * @param nodeList
	 * @return
	 */
	private Map<String,List<Node>> classifiedNodes(List<Node> nodeList){
		Map<String,List<Node>> map=new HashMap<String, List<Node>>();
		for(Node node:nodeList){
			if(Node.HTML_ELEMENT_TAG.equals(node.getNodeType())){
				if(map.containsKey(node.getNodeName())){
					map.get(classifiedKeyValue(node)).add(node);
				}else{
					map.put(classifiedKeyValue(node), ListUtil.toList(node));
				}
			}else{
				String classifiedKey=classifiedKeyValue(node);
				if(map.containsKey(classifiedKey)){
					map.get(classifiedKey).add(node);
				}else{
					map.put(classifiedKey, ListUtil.toList(node));
				}
			}
		}
		return map;
	}
	
	/**
	 * 聚合规则
	 * @param node
	 * @return
	 */
	public abstract String classifiedKeyValue(Node node);

}
